//index.js
//获取应用实例
const Promise = require('../../services/promise'); 
const qrcodeService = require('../../services/qrcodeService');
const activityService = require('../../services/activityService');
const userService = require('../../services/userService');
const WxParse = require('../../wxParse/wxParse.js');
var app = getApp()
Page({
  data: {
    productId: '',
    fangweipop: false, //防伪弹窗
    fwError: false, //防伪验证是否通过
    qrcode_type: 2, //2贴码弹窗，1赋码不弹
    se: '',
    aptitude: {},
    price_intro: '',//未中奖说明
    popup_method: 0,//抽奖弹窗样式
    showPop:false, //是否点击抽奖
    qrcodeInfo: {},
    errormsg: '',
    code: 1,
    activity: {},
    product: {},
    company: {},
    module_info: [],
    images: [],
    bodybg: '#fff',
    swiperHeight: 0,
    error: false,
    errorMsg: '',
    //TODO 接口模拟数据
    // prize:{
    //     code:1,
    //     msg: '亲，您已兑换过',
    //     data: {
    //     if_win:1,
    //     store_url: '',
    //     prize_info: {
    //       activity_id: 66,
    //       freeze_num: 0,
    //       id: 255,
    //       money: '0.81',
    //       money_range: '1.10',
    //       num: 10,
    //       sub_type: 1,
    //       surplus_num: 10,
    //       tips: '<br />可以点击【我的奖品】查看',
    //       type: 1,
    //       coupons_info: {
    //         validity_date: ''
    //       }
    //     }
    //   }
    // },
    prize: {}
  },

  bindFWInput: function(e) {
    this.setData({
      se: e.detail.value
    })
  },
  validateFW: function(){
    var that = this;
    var user = wx.getStorageSync('user');
    if(user) {
        if(!user.openid) {
          this.setData({
            error:true,
            errorMsg: '没有获取到openid'
          });
          setTimeout(function(){
            that.setData({
              error:false
            });
          },2000);
          return;
        }
        if(this.data.se == '') {
          that.setData({
            fwError: true
          });
          return;
        }
      var qrcodeInfo = this.data.qrcodeInfo;
      var mid = qrcodeInfo.mid;
      var sn = qrcodeInfo.sn;
      var openid = user.openid;
      activityService.fangweiVerify(this.data.qrcode_type,this.data.se,openid,mid,sn).then((data=>{
        if(data.code == 1){
          that.setData({
            fwError: false
          });
          var se = data.data.se;
          var fangweiInfo = data.data.fangweiInfo;
          var num_time = data.data.num_time;
          if(!num_time) {
            num_time = '';
          }
          var productId = that.data.productId;
          that.setData({
            fwError: false,
            se: '',
            fangweipop: false
          });
          wx.navigateTo({
            url: `../fangwei/fangwei?se=${se}&fangweiInfo=${fangweiInfo}&num_time=${num_time}&pid=${productId}`
          });
        } else{
          that.setData({
            fwError: true
          });
        }
         
        }),(error=>{
          that.setData({
            error:true,
            errorMsg: '防伪验证失败'
          });
          setTimeout(function(){
            that.setData({
              error:false
            });
          },2000);
        }));
      }
  },
  naviFagnwei: function() {
    var that = this;
    //弹窗
    if(this.data.qrcode_type == 2) {
      this.setData({
        fwError: false,
        fangweipop: true,
        se: ''
      });
    // 到防伪验证页面
    } else {
      var user = wx.getStorageSync('user');
      if(user) {
        if(!user.openid) {
          this.setData({
            error:true,
            errorMsg: '没有获取到openid'
          });
          setTimeout(function(){
            that.setData({
              error:false
            });
          },2000);
          return;
        }
        var qrcodeInfo = this.data.qrcodeInfo;
        var mid = qrcodeInfo.mid;
        var sn = qrcodeInfo.sn;
        var openid = user.openid;
        activityService.fangweiVerify(this.data.qrcode_type,this.data.se,openid,mid,sn).then((data=>{
        if(data.code ==1 ){
          var se = data.data.se;
          var fangweiInfo = data.data.fangweiInfo;
          var num_time = data.data.num_time;
          if(!num_time) {
            num_time = '';
          }
          var productId = that.data.productId;
          wx.navigateTo({
            url: `../fangwei/fangwei?se=${se}&fangweiInfo=${fangweiInfo}&num_time=${num_time}&pid=${productId}`
          });
        } else {
          that.setData({
            error:true,
            errorMsg: data.msg
          });
          setTimeout(function(){
            that.setData({
              error:false
              });
            },2000);  
        }
      }),(error=>{
        that.setData({
          error:true,
          errorMsg: '防伪验证失败'
        });
        setTimeout(function(){
          that.setData({
            error:false
          });
        },2000);
      }));

      }
      
      
    }
  },
  closeFWPop: function() {
    this.setData({
      fangweipop: false
    });
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../kefu/kefu'
    })
  },
  drawPrize: function() {
    var that = this;
    var user = wx.getStorageSync('user');
    if(user) {
      if(!user.openid) {
        this.setData({
          error:true,
          errorMsg: '没有获取到openid'
        });
        setTimeout(function(){
          that.setData({
            error:false
          });
        },2000);
        return;
      }
      var params = {};
      var qrcodeInfo = this.data.qrcodeInfo;
      params.activity_id = qrcodeInfo.activity_id;
      params.mid = qrcodeInfo.mid;
      params.sn = qrcodeInfo.sn;
      params.work_sn = qrcodeInfo.work_sn;
      params.qrcode = this.data.qrcode;
      params.nickname = user.nickName;
      params.openid = user.openid;
      userService.drawPrize(params).then((data=>{
        if(data.code == 0) {
          var msg = data.msg;
          var msgs = msg.split('<br />');
          data.msgs = msgs;
        }
        this.setData({
          showPop: true,
          prize: data
        });
      }),(error=>{
        this.setData({
          error:true,
          errorMsg: '抽奖接口异常'
        });
        setTimeout(function(){
          that.setData({
            error:false
          });
        },2000);
      }));
    } else {
      //获取用户信息
      app.getUserInfo(function(userInfo){
        //更新数据
        //that.getIndexInfo();
        that.setData({
          userInfo:userInfo
        })
      });
    }
    
  },
  closePrizePop: function() {
    this.setData({
      showPop: false
    });
  },
  navigateToIndex: function(){
    wx.reLaunch({
      url: '../index/index'
    })
  },

  navigateToAptitude: function(){
    var aptitude = this.data.aptitude;
    wx.navigateTo({
      url: `../aptitude/aptitude?rszlurl=${aptitude.rszlurl}&rszpurl=${aptitude.rszpurl}&sgsurl=${aptitude.sgsurl}&sikshyurl=${aptitude.sikshyurl}`
    })
  },
  bindScanCode: function() {
    app.bindScanCode();
  },
  imageLoad: function(e) {
     var $width=e.detail.width,    //获取图片真实宽度
         $height=e.detail.height;
      var image=this.data.images;      //将图片的datadata-index作为image对象的key,然后存储图片的宽高值
      var percent = e.target.dataset.percent;
      if(e.target.dataset.type == 'swiper') {
        var screenWidth_rpx = wx.getSystemInfoSync().screenWidth;
        var ratio=$width/$height;    //图片的真实宽高比例
        var viewWidth=screenWidth_rpx,           //设置图片显示宽度，左右留有16rpx边距
            viewHeight=screenWidth_rpx/ratio;    //计算的高度值
        if(percent) {
          viewWidth = viewWidth * percent;
          viewHeight = viewHeight * percent;
        }
        image[e.target.dataset.key]={
         width:viewWidth,
         height:viewHeight
        }
        //轮播图片最小高度
        if(this.data.swiperHeight == 0 || this.data.swiperHeight > viewHeight) {
          this.setData({
            swiperHeight: viewHeight
          });
        }
      } else {
        image[e.target.dataset.key]={
         width:$width,
         height:$height
        }
      }
      
      this.setData({
           images:image
      })
  },
  getActivityInfo(activity_id,mid) {
    var that = this;
    Promise.all([activityService.getActivityStore(activity_id),activityService.getMerchantInfo(mid)]).then((results) =>{
      var activity = results[0].data;
      var company = results[1].data;
      // 获取产品信息
      activityService.getProductInfo(activity.product_id).then((data=>{
        that.setData({
          product: data.data,
          productId: activity.product_id
        });
      }),(error=>{
        this.setData({
          error:true,
          errorMsg: '获取产品信息失败'
        });
        setTimeout(function(){
          that.setData({
            error:false
          });
        },2000);
      }));

      activity.start_date = activity.start_date.substring(0,10);
      activity.end_date = activity.end_date.substring(0,10);
      var module_info = activity.module_info[0];
      module_info = module_info.replace(/\/merchant\/resource\/image/g,'/resources');
      module_info = JSON.parse(module_info);
      for(var i = 0; i < module_info.length; i++) {
        var item = module_info[i];
        if(item.type == 'activity') {
          this.setData({
            bodybg: item.bodybg,
            price_intro: item.price_intro,
            popup_method: item.popup_method
          });
          WxParse.wxParse('activityint','html', item.activity_intro, that,0);
          wx.getSystemInfo({
            success:function(obj) {
              var clientWidth = obj.screenWidth;
              var deviceWidth = item.deviceWidth;
              var upbtn_top  = item.upbtn_top;
              var upbtnWidth = item.upbtnWidth;
              upbtn_top = (clientWidth * upbtn_top)/deviceWidth;
              upbtnWidth = parseFloat(upbtnWidth);
              upbtnWidth = (clientWidth * upbtnWidth)/deviceWidth;
              //将px单位转成rpx
              //upbtnWidth = 750 * upbtnWidth/375;
              //upbtn_top = 750 * upbtn_top/375;
              item.upbtn_top = upbtn_top;
              item.upbtnWidth = upbtnWidth;
            }
          });
        }
        if(item.type == 'aptitude') {
          this.setData({
            aptitude: item
          });
        }
      }
      this.setData({
        activity: activity,
        company: company,
        module_info: module_info,
        code: 1
      });
    },(error=>{
      this.setData({
          error:true,
          errorMsg: '获取活动信息失败！'
        });
        setTimeout(function(){
          that.setData({
            error:false
          });
        },2000);
    }));
  },
  setActivityInfo(openid,user,latitude,longitude){
    var params = {};
    params.openid = openid;
    if(latitude) {
      params.lat = latitude;
    }
    if(longitude) {
      params.lng = longitude;
    }
    if(app.globalData.activity_id) {
      params.activity_id = app.globalData.activity_id;
    }

    if(app.globalData.mid) {
      params.mid = app.globalData.mid;
    }

    if(app.globalData.qrcode) {
      params.qrcode = app.globalData.qrcode;
    }
    userService.login(params).then((data) => {
      }, (error) => {
    });
  },
  onLoad: function (options) {
    var that = this;
    qrcodeService.qrcodeAnaly(options.qrcode).then((data) => {
      if(data.code == 0 || data.code == 1) {
        this.setData({
          qrcodeInfo: data.data,
          qrcode: options.qrcode,
          qrcode_type: data.data.type,
          se: data.data.se
        });
        this.getActivityInfo(data.data.activity_id,data.data.mid);
        //调用应用实例的方法获取全局数据
        app.globalData.activity_id = data.data.activity_id;
        app.globalData.qrcode = options.qrcode;
        app.globalData.mid = data.data.mid;
        var user = wx.getStorageSync('user');
        if(user) {
          if(!user.openid) {
            this.setData({
              error:true,
              errorMsg: '没有获取到openid！'
            });
            setTimeout(function(){
              that.setData({
                error:false
              });
            },2000);
            return;
          }
          wx.getLocation({
                  success:function(data) {
                    var latitude = data.latitude;
                    var longitude = data.longitude;
                    that.setActivityInfo(user.openid,user,latitude,longitude); 
                    console.info('setActivityInfo');
                    console.info(user);
                  },
                  fail: function(error) {
                    that.setActivityInfo(user.openid,user); 
                    console.info('location fail');
                    console.info('setActivityInfo');
                  }
                });
        } else {
          //获取用户信息
          app.getUserInfo(function(userInfo){
            //更新数据
            //that.getIndexInfo();
            that.setData({
              userInfo:userInfo
            })
          });
        }
        
      } else {
        var errormsg;
        switch (data.code)
        {
        case 101:
          errormsg='此二维码未激活';
          break;
        case 102:
          errormsg='此二维码已作废';
          break;
        case 103:
          errormsg='此二维码关联项目被删除,暂时无法访问';
          break;
        case 104:
          errormsg='二维码信息有误';
          break;
        case 201:
          errormsg='努力准备红包中';
          break;
        case 301:
          errormsg='您的扫码数已经达到上限';
          break;
        case 404:
          errormsg='非法请求';
          break;
        case 999:
          msg='系统更新中........';
          break;
        default:
          msg='未知状态';
        }
        this.setData({
          errormsg: errormsg,
          code: data.code
        });
      }
        
      }, (error) => {
    });

    
    
    app.editTabBar();//添加tabBar数据  
  }
})
